﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
using AppExample;
using Newtonsoft.Json;
using LinqToTwitter;

namespace SafeTraveller.Controllers
{
    public class ValuesController : ApiController
    {
        private const String ConsumerKey = "ay6t0YBkUs5Qm0mGQSYCqg";
        private const String ConsumerSecret = "WKztDXhDZXXOflRX4kMFMiFZMxpA3GRamymvfoqOI";
        private const String tmpQuery = "https://api.twitter.com/1.1/search/tweets.json?q=include_entities=epidemic";

        readonly IOAuthCredentials credentials = new SessionStateCredentials();

        MvcAuthorizer auth;
        TwitterContext twitterCtx;

        public IEnumerable<string> Get()
        {
            return new List<string>{"1","2"};
        }

        /*private void tryTwitter()
        {
            if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
            {
                credentials.ConsumerKey = ConsumerKey;
                credentials.ConsumerSecret = ConsumerSecret;
            }

            auth = new MvcAuthorizer
            {
                Credentials = credentials
            };

            // internally, this doesn't execute if BeginAuthorization hasn't been called yet
            //  but it will execute after the user authorizes your application
            auth.CompleteAuthorization(Request.Url);

            // this will only execute if we don't have all 4 keys, which is what IsAuthorized checks
            if (!auth.IsAuthorized)
            {
                Uri specialUri = new Uri(Request.Url.ToString());

                // url param is optional, it lets you specify the page Twitter redirects to.
                // You can use it to complete the OAuth process on another action/controller - in which
                // case you would move auth.CompleteAuthorization to that action/controller.
                return auth.BeginAuthorization(specialUri);
            }

            twitterCtx = new TwitterContext(auth);

            List<TweetViewModel> friendTweets =
                (from tweet in twitterCtx.Status
                 where tweet.Type == StatusType.User &&
                       tweet.ScreenName == "JoeMayo"
                 select new TweetViewModel
                 {
                     ImageUrl = tweet.User.ProfileImageUrl,
                     ScreenName = tweet.User.Identifier.ScreenName,
                     Tweet = tweet.Text
                 })
                .ToList();

            return View(friendTweets);
        }*/

        // GET api/values
        public void Get(string datefrom, string dateto, string type)
        {
            String path = AppDomain.CurrentDomain.BaseDirectory;
            System.IO.StreamWriter file = new System.IO.StreamWriter(path + "data.csv");
            file.WriteLine("date,territory,count,risk");

            StringBuilder sb = new StringBuilder();
            DateTime from, to;
            if (!DateTime.TryParse(datefrom, out from))
                from = new DateTime(2012, 1, 1);
            if (!DateTime.TryParse(dateto, out to))
                to = new DateTime(2015, 1, 1);
            using (StreamReader sr = new StreamReader(path+"srcdata.csv"))
            {
                sr.ReadLine();
                while (!sr.EndOfStream)
                {
                    String read = sr.ReadLine();
                    String[] row = read.Split(',');
                    DateTime curtime = DateTime.Parse(row[0]);
                    bool coin = type.Contains(row[3]);
                    if (curtime >= from && curtime <= to && coin)
                    {
                        file.WriteLine(read);
                    }
                }
            }

            file.Flush();
            file.Close();

            UploadData();


            
            //var dateFrom = DateTime.Parse(datefrom, new CultureInfo("ru-RU", false));
            //var dateTo = DateTime.Parse(dateto, new CultureInfo("ru-RU", false));

            //UploadData();

        }


        public static string CalculateSHA1(string text, Encoding enc)
        {
            byte[] buffer = enc.GetBytes(text);
            SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider();
            return BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "").ToLower();
        }

        private void UploadData()
        {
            String path = AppDomain.CurrentDomain.BaseDirectory;
            FileStream fs = new FileStream(path + "data.csv", FileMode.Open, FileAccess.Read);
            byte[] data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);
            fs.Close();

            // Generate post objects
            Dictionary<string, object> postParameters = new Dictionary<string, object>();
            postParameters.Add("filename", "data.csv");
            postParameters.Add("fileformat", "csv");
            postParameters.Add("file", new FormUpload.FileParameter(data, "data.csv", "application/vnd.ms-excel"));

            // Create request and receive response
            string postURL = ConfigurationSettings.AppSettings["url"] + "api?s=ImportService&withheader=1&name=data&delimiter=,";
            //"country","series","Unit","Date","Value"

            List<Field> fields = new List<Field>();
            fields.Add(new Field() { Name = "date", TypeName = "timestamp" });
            fields.Add(new Field() { Name = "territory", TypeName = "string" });
            fields.Add(new Field() { Name = "count", TypeName = "double" });
            fields.Add(new Field() { Name = "risk", TypeName = "string" });
            
            postURL += "&fields=" + JsonConvert.SerializeObject(fields);
            string userAgent = "Someone";
            HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL,
                userAgent,
                postParameters,
                CalculateSHA1(ConfigurationSettings.AppSettings["secret"] + ConfigurationSettings.AppSettings["token"], Encoding.UTF8),
                int.Parse(ConfigurationSettings.AppSettings["appid"]));

            // Process response
            StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
            string fullResponse = responseReader.ReadToEnd();
            webResponse.Close();
            //info.Text = fullResponse;

            Schema s = JsonConvert.DeserializeObject<Schema>(fullResponse);

            //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ButtonClickScript", "CI.openSource(" + s.Key + ");", true);
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }

        

       
    }

}